package textEngine.similarityFinderTest;


public class HistogramDistanceManhattanPesata {
	/*
	 * E' come la HistogramDistance solo che qui faccio la distanza Manhattan e basta
	 * e assegno un peso fissato alle prime lettere delle parole
	 * RISULTATO--> funziona del cazzo
	 * 
	 */
	public static final String euclidean="Euclidean";
	public static final String manhattan="Manhattan";
	public static final String normalizedWeighetdManhattan="Normalized-Weighted-Manhattan";
	
	private static int firstCharacterWeight=2; 
	
	public static double getDistance(String s1, String s2,String distanceType){
		/**
		 * ATTENZIONE: NON SONO STATI CONSIDERATE LE PAROLE ACCENTATE (NON DANNO CONTRIBUTO!!)
		 * NON E' STATO NORMALIZZATO!!!
		 */
		//TODO: Da considerare gli ACCENTI!!!!
	

		double dist=0.0;
		
		
		if (distanceType.equals(normalizedWeighetdManhattan)){
			int[] s1Hist= computeWeighetdHistogram(s1);
			int[] s2Hist= computeWeighetdHistogram(s2);
			int normalizationFactor=computeNormalizationFactor(s1Hist,s2Hist);
			dist = manhattanDistance(s1Hist, s2Hist)/( normalizationFactor);
		}
		return dist;
	}
	
	

	private static int computeNormalizationFactor(int[] s1Hist, int[] s2Hist) {
		int tmp=0;
		for (int i = 0; i < s2Hist.length; i++) {
			tmp=tmp+s1Hist[i]+s2Hist[i];
		}
		return tmp;
	}



	private static double manhattanDistance(int[] s1Hist,int[] s2Hist){
		if(s1Hist.length!=s2Hist.length) return -1;
		double dist=0.0;
		for(int i=0; i<s1Hist.length;i++){
			dist+=Math.abs(s1Hist[i]-s2Hist[i]);
		}
		return dist;
	}

	
	
	private static int[] computeHistogram(String s){
		
		//Non si distingua upper da lower case
		s= s.toLowerCase();
		int[] sHistogram= new int[26];
		
		//initializze
		for(int i=0; i<26; i++){
			sHistogram[i]=0;	
		}
		
		for(int i=0; i<s.length();i++){
			if(s.charAt(i)-97<26 && s.charAt(i)-97>=0){
				sHistogram[s.charAt(i)-97]++;
			}
		}
		return sHistogram;
		
	}
	private static int[] computeWeighetdHistogram(String s) {
		
		//Effettua una pesatura del primo carattere 
		//delle parole (es. Anna Lucci --> A ed L vengono moltiplicate per un fattore)
		
		
		
		//Non si distingua upper da lower case
		s= s.toLowerCase();
		int[] sHistogram= new int[26];
		
		//initializze
		for(int i=0; i<26; i++){
			sHistogram[i]=0;	
		}
		boolean firstCharacther=true;
		for(int i=0; i<s.length();i++){
			if(s.charAt(i)-97<26 && s.charAt(i)-97>=0){
				if (firstCharacther){ 
					sHistogram[s.charAt(i)-97]+=firstCharacterWeight;
					firstCharacther=false;
				}
				else{
					sHistogram[s.charAt(i)-97]++;
				}
				
			}
			else if(Character.isWhitespace(s.charAt(i))){
				firstCharacther=true;
			}
		}
		return sHistogram;
	}

}

